$(function () {
    query();
    $(".js-simple-query").unbind("click").click(function () {
        $("#myTable").bootstrapTable("refresh");
    })
    getCodeClass("problemTypeP", "pro_problem_type");
    jeDate("#beginTimeQuery", {
        format: "YYYY-MM-DD"
    });
    jeDate("#endTimeQuery", {
        format: "YYYY-MM-DD"
    });
    jeDate("#finishTime", {
        format: "YYYY-MM-DD"
    });
    $.ajax({
        url: "/ret/proget/getProSortTree",
        type: "post",
        dataType: "json",
        success: function (data) {
            var topNode = [{
                sortName: "全部",
                isParent: "false",
                sortId: ""
            }];
            var newTreeNodes = topNode.concat(data);
            $.fn.zTree.init($("#menuTree"), setting1, newTreeNodes);
        }
    });
    $("#proSortQuery").unbind("click").click(function (e) {
        e.stopPropagation();
        $("#menuContent").css({
            "width": $(this).outerWidth() + "px",
            "left": $(this).offset().left + "px"
        }).slideDown(200);
    });
    $("body").unbind("click").click(function () {
        $("#menuContent").hide();
    });
    $("#menuContent").unbind("click").click(function (e) {
        e.stopPropagation();
    });
})

function query() {
    $("#myTable").bootstrapTable({
        url: '/ret/proget/getMyTaskWorkList',
        method: 'post',
        contentType: 'application/x-www-form-urlencoded',
        toolbar: '#toobar',//工具列
        striped: true,//隔行换色
        cache: false,//禁用缓存
        pagination: true,//启动分页
        sidePagination: 'server',//分页方式
        pageNumber: 1,//初始化table时显示的页码
        pageSize: 10,//每页条目
        showFooter: false,//是否显示列脚
        showPaginationSwitch: true,//是否显示 数据条数选择框
        sortable: true,//排序
        search: true,//启用搜索
        sortOrder: "asc",
        showColumns: true,//是否显示 内容列下拉框
        showRefresh: true,//显示刷新按钮
        idField: 'taskId',//key值栏位
        clickToSelect: true,//点击选中checkbox
        pageList: [10, 20, 30, 50],//可选择单页记录数
        queryParams: queryParams,
        columns: [{
            checkbox: true
        }, {
            field: 'num',
            title: '序号',//标题  可不加
            width: '50px',
            formatter: function (value, row, index) {
                return index + 1;
            }
        }, {
            field: 'text',
            width: '150px',
            title: '任务名称',
            formatter: function (value, row, index) {
                return "<a href=\"javascript:void(0);details('" + row.proId + "','" + row.taskId + "')\" style='cursor: pointer'>" + value + "</a>";
            }
        }, {
            field: 'title',
            width: '150px',
            title: '项目名称'
        }, {
            field: 'sortName',
            width: '50px',
            title: '项目分类'
        }, {
            field: 'startDate',
            width: '50px',
            title: '开始日期'
        }, {
            field: 'duration',
            width: '50px',
            title: '工期'
        }, {
            field: 'progress',
            width: '50px',
            title: '进度',
            formatter: function (value, row, index) {
                return value + "%";
            }
        }, {
            field: 'opt',
            title: '操作',
            align: 'center',
            width: '150px',
            formatter: function (value, row, index) {
                return createOptBtn(row.proId, row.taskId, row.status, row.sortId);
            }
        }],
        onClickCell: function (field, value, row, $element) {
        },
        responseHandler: function (res) {
            if (res.status == "500") {
                console.log(res.msg);
            } else if (res.status == "100") {
                layer.msg(sysmsg[res.msg]);
            } else {
                return {
                    total: res.list.total, //总页数,前面的key必须为"total"
                    rows: res.list.list
                    //行数据，前面的key要与之前设置的dataField的值一致.
                };
            }
        }
    });
}

function queryParams(params) {
    var temp = {
        search: params.search,
        pageSize: this.pageSize,
        pageNumber: this.pageNumber,
        sort: params.sort,
        sortOrder: params.order,
        proSort: $("#proSortQuery").val(),
        endTime: $("#endTimeQuery").val(),
        beginTime: $("#beginTimeQuery").val()
    };
    return temp;
};

function createOptBtn(proId, taskId, status, sortId) {
    let html = "";
    if (status != "2") {
        html += "<a href=\"javascript:void(0);doProcess('" + taskId + "')\" class=\"btn btn-primary btn-xs\">汇报</a>&nbsp;&nbsp;"
            + "<a href=\"javascript:void(0);setBpmFlow('" + proId + "','" + taskId + "','" + sortId + "')\" class=\"btn btn-success btn-xs\">流程</a>&nbsp;&nbsp;"
            + "<a href=\"javascript:void(0);sendProblem('" + taskId + "')\" class=\"btn btn-darkorange btn-xs\" >反馈</a>&nbsp;&nbsp;"
    }
    if (status == "0") {
        html += "<a href=\"javascript:void(0);doSetStop('" + taskId + "')\" class=\"btn btn-purple btn-xs\">挂起</a"
    } else if (status == "1") {
        html += "<a href=\"javascript:void(0);revBack('" + taskId + "')\" class=\"btn btn-success btn-xs\">恢复</a>"
    }
    return html;
}

function setBpmFlow(proId, taskId, sortId) {
    $("#title").val("");
    $("#setbpmmodal").modal("show");
    $.ajax({
        url: "/ret/proget/getProSortById",
        type: "post",
        dataType: "json",
        data: {
            sortId: sortId
        },
        success: function (data) {
            if (data.status == "200") {
                getFlowNameByFlowIds(data.list.flowIds);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                console.log(data.msg);
            }

        }
    });
    $(".js-add-bpm").unbind("click").click(function () {
        startBpm(proId, taskId);
    });
}


function revBack(taskId) {
    if (confirm("您确定要恢复当前任务吗？")) {
        $.ajax({
            url: "/set/proset/updateProTask",
            type: "post",
            dataType: "json",
            data: {
                taskId: taskId,
                status: "0"
            },
            success: function (data) {
                if (data.status == "200") {
                    layer.msg(sysmsg[data.msg]);
                    $("#myTable").bootstrapTable("refresh");
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    console.log(data.msg);
                }

            }
        });
    }
}

function doSetStop(taskId) {
    if (confirm("您确定要挂起当前任务吗？")) {
        $.ajax({
            url: "/set/proset/updateProTask",
            type: "post",
            dataType: "json",
            data: {
                taskId: taskId,
                status: "1"
            },
            success: function (data) {
                if (data.status == "200") {
                    layer.msg(sysmsg[data.msg]);
                    $("#myTable").bootstrapTable("refresh");
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    console.log(data.msg);
                }

            }
        });
    }
}

function doProcess(taskId) {
    document.getElementById("form1").reset();
    $("#show_attach").html("");
    $("#attach").attr("data_value", "");
    $("#processModel").modal("show");
    $(".js-process").unbind("click").click(function () {
        $.ajax({
            url: "/set/proset/createProcess",
            type: "post",
            dataType: "json",
            data: {
                taskId: taskId,
                title: $("#title").val(),
                finishTime: $("#finishTime").val(),
                process: $("#process").val(),
                resContent: $("#resContent").val(),
                attach: $("#attach").attr("data_value")
            },
            success: function (data) {
                if (data.status == "200") {
                    layer.msg(sysmsg[data.msg]);
                    $("#myTable").bootstrapTable("refresh");
                    $("#processModel").modal("hide");
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    console.log(data.msg);
                }
            }
        });
    })

}

function sendProblem(proId, taskId) {
    document.getElementById("form2").reset();
    $("#problemModel").modal("show");
    $("#show_attachP").empty();
    $("#attachP").attr("data_value", "");
    $(".js-problem").unbind("click").click(function () {
        $.ajax({
            url: "/set/proset/insertProProblem",
            type: "post",
            dataType: "json",
            data: {
                proId: proId,
                taskId: taskId,
                title: $("#titleP").val(),
                problemType: $("#problemTypeP").val(),
                remark: $("#remarkP").val(),
                attach: $("#attachP").attr("data_value")
            },
            success: function (data) {
                if (data.status == "200") {
                    layer.msg(sysmsg[data.msg]);
                    $("#problemModel").modal("hide");
                } else if (data.status == "100") {
                    layer.msg(sysmsg[data.msg]);
                } else {
                    console.log(data.msg);
                }
            }
        });
    })
}

function details(proId, taskId) {
    window.open("/app/core/project/protaskdetails?proId=" + proId + "&taskId=" + taskId);
}

var setting1 = {
    async: {
        enable: true,// 设置 zTree 是否开启异步加载模式
        url: "/ret/proget/getProSortTree",// Ajax 获取数据的 URL 地址
        autoParam: ["sortId"],// 异步加载时需要自动提交父节点属性的参数
    },
    view: {
        dblClickExpand: false,
        selectedMulti: false
        //禁止多选
    },
    data: {
        simpleData: {
            enable: true,
            idKey: "sortId",
            pIdKey: "levelId",
            rootPId: "0"
        },
        key: {
            name: "sortName"
        }
    },
    callback: {
        onClick: function (e, treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("menuTree"), nodes = zTree.getSelectedNodes(), v = "";
            vid = "";
            nodes.sort(function compare(a, b) {
                return a.id - b.id;
            });
            for (var i = 0, l = nodes.length; i < l; i++) {
                v += nodes[i].sortName + ",";
                vid += nodes[i].sortId + ",";
            }
            if (v.length > 0)
                v = v.substring(0, v.length - 1);
            if (vid.length > 0)
                vid = vid.substring(0, vid.length - 1);
            var idem = $("#proSortQuery");
            idem.val(v);
            idem.attr("data-value", vid);
        }
    }
};

function getFlowNameByFlowIds(flowIds) {
    $.ajax({
        url: "/ret/bpmget/getFlowNameByFlowIds",
        type: "post",
        dataType: "json",
        data: {flowIds: flowIds},
        success: function (data) {
            if (data.status == "200") {
                let infoList = data.list;
                let html = "";
                for (let i = 0; i < infoList.length; i++) {
                    html += "<option value='" + infoList[i].flowId + "'>" + infoList[i].flowName + "</option>";
                }
                $("#flowId").html(html);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                console.log(data.list);
            }
        }
    })
}


function startBpm(proId, taskId) {
    $.ajax({
        url: "/set/proset/startProBpmRecordBpm",
        type: "post",
        dataType: "json",
        data: {
            proId: proId,
            taskId: taskId,
            flowId: $("#flowId").val(),
            title: $("#bpmTitle").val()
        },
        success: function (data) {
            if (data.status == "500") {
                console.log(data.msg);
            } else if (data.status == "100") {
                layer.msg(sysmsg[data.msg]);
            } else {
                layer.msg(sysmsg[data.msg]);
                $("#setbpmmodal").modal("hide");
                parent.openNewTabs(data.redirect, "流程待办");
            }
        }
    })
}
